// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently.
import { getNode, HvigorNode, HvigorTask, hvigor } from '@ohos/hvigor'
import { appTasks, OhosPluginId, OhosAppContext, AppJson, OhosHarContext, OhosHapContext } from '@ohos/hvigor-ohos-plugin';
import fs from 'fs';

// 获取当前hvigorNode节点对象
const node: HvigorNode = getNode(__filename);
hvigor.buildFinished(() => {
  // 构建结束后。复制hap，将生成的hap重命名为带有版本号的文件名
  console.log(`复制hap：${node.getNodeName()}`);
  const appContext = node.getContext(OhosPluginId.OHOS_APP_PLUGIN) as OhosAppContext
  const appJson5: AppJson.AppOptObj = appContext.getAppJsonOpt()
  const versionName = appJson5.app.versionName
  const projectName = appContext.getProjectName()
  const entryNode = node.getSubNodeByName('entry')
  console.log(`节点名称：${entryNode.getNodeName()}`)
  const hapContext = entryNode?.getContext(OhosPluginId.OHOS_HAP_PLUGIN) as OhosHapContext
  const moduleName = entryNode?.getNodeName()
  const modulePath = entryNode?.getNodePath()
  console.log(`模块名称：${moduleName}`);
  console.log(`模块路径：${modulePath}`);
  const originFilePath = `${modulePath}/build/default/outputs/default/${moduleName}-default-signed.hap`
  const targetFileDir = `${modulePath}/build/default/outputs/default/target`
  const targetFilePath = `${modulePath}/build/default/outputs/default/target/${projectName}-${versionName}-signed.hap`
  fs.mkdir(targetFileDir, {recursive: true}, (err) => {})
  fs.copyFile(originFilePath, targetFilePath, () => {})
})

export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}